<template>
  <div
      ref="oneFileOrDir"
      class="one-file-or-dir"
  >
    <el-space wrap :class="typeData === 'folder' ? 'folder-icon-wrap' : ''">
      <component :is="fileType(typeData)"></component>
    </el-space>
    <div class="file-or-dir-wrap">{{ fileNameData }}</div>
    <el-divider border-style="dashed"/>
    <div class="author-and-date">
      <el-space wrap class="author">{{ authorData }}</el-space>
      <span class="date">{{ DateFormatPipe(dateData, 'yyyy-MM-dd') }}</span>
    </div>
  </div>
  <div
      ref="oneFileOrDirHover"
      class="one-file-or-dir-hover"
  >
    <el-space wrap :class="typeData === 'folder' ? 'folder-icon-wrap' : ''">
      <component :is="fileType(typeData)"></component>
    </el-space>
    <div class="file-or-dir-wrap">{{ fileNameData }}</div>
    <div style="flex: 1"></div>
    <div
        @click.stop class="more">
      <el-dropdown trigger="click" @visible-change="visibleChange" popper-class="more-popper">
        <div class="icon-wrap"><img :src="require('@/assets/img/more.png')"/></div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="downloadDocument()" v-if="documentId">
              <el-icon>
                <ArrowDownload/>
              </el-icon>&nbsp;下载
            </el-dropdown-item>
            <el-dropdown-item @click="removefile()">
              <el-icon>
                <DeleteIcon class="delete-icon"/>
              </el-icon>&nbsp;删除
            </el-dropdown-item>
            <el-dropdown-item @click="moveFileOrDirectory()"
                              v-if="level !== 1 && ancestors.indexOf(',')!==-1 && ancestors.split(',').indexOf('1010')===-1&&ancestors.split(',').indexOf('1002')===-1">
              <el-icon>
                <MoveToIcon/>
              </el-icon>&nbsp;移动到
            </el-dropdown-item>
            <el-dropdown-item @click="echoName()">
              <el-icon>
                <EditIcon/>
              </el-icon>&nbsp;重命名
            </el-dropdown-item>
            <template v-if="documentId">
              <el-dropdown-item v-if="flag === 0" @click="addCollection()">
                <el-icon>
                  <StarIcon/>
                </el-icon>&nbsp;收藏
              </el-dropdown-item>
              <el-dropdown-item v-if="flag === 1" @click="removeCollection()">
                <el-icon>
                  <StarIcon/>
                </el-icon>&nbsp;取消收藏
              </el-dropdown-item>
            </template>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <div class="icon-wrap share" v-if="documentId"><img :src="require('@/assets/img/share.png')" @click="copyText"/>
    </div>
    <div
        @click.stop v-if="typeData === 'folder' && level === 1 " class="more">
      <el-dropdown trigger="click" @visible-change="visibleChange" popper-class="more-popper">
        <div class="icon-wrap">
          <el-icon class="new">
            <Plus/>
          </el-icon>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item v-if="directoryId!==1010 && directoryId!==1002" @click.stop.prevent="uploadFileButton">
              <el-icon>
                <Upload></Upload>
              </el-icon>&nbsp;上传文件
            </el-dropdown-item>
            <el-dropdown-item @click.stop="openNewDirDialog">
              <el-icon>
                <Folder/>
              </el-icon>&nbsp;新建文件夹
            </el-dropdown-item>
            <el-dropdown-item v-if="directoryId!==1010&&directoryId!==1002" @click.stop="openNewMarkdown">
              <el-icon>
                <MarkdownArrow/>
              </el-icon>&nbsp;新建Markdown
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <div @click.stop
         v-if="typeData === 'folder' && level === 2"
         class="more">
      <el-dropdown trigger="click" placement="bottom-start" popper-class="more-popper"
                   @visible-change="visibleChange">
        <div class="icon-wrap">
          <el-icon class="new">
            <Plus/>
          </el-icon>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item
                @click.stop.prevent="uploadFileButton">
              <el-icon>
                <Upload></Upload>
              </el-icon>&nbsp;上传文件
            </el-dropdown-item>
            <el-dropdown-item @click.stop="openNewMarkdown" v-if="parentDirectoryId!==1010&&parentDirectoryId!==1002">
              <el-icon>
                <MarkdownArrow/>
              </el-icon>&nbsp;新建Markdown
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
  <el-dialog
      ref="uploadFileForm"

      @click="stopProp"
      draggable
      v-model="dialogVisible"
      @close="uploadDialogClose"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      destroy-on-close
      @before-close="handleClosed"
      width="123.2rem">
    <template #header>
      <span class="el-dialog__title">上传文件</span>
    </template>
    <el-card class="upload-card" shadow="never">
      <el-form label-position="right" :model="uploadForm">
        <el-form-item prop="fileName">
          <upload-file ref="uploadRef" :type="uploadForm.type" @removeUpload="removeUploadFile"
                       @onProgress="onProgressUpload"
                       @allUploadSuccess="allUploadSuccess" @uploadSuccess="fillForm"></upload-file>
        </el-form-item>
      </el-form>
    </el-card>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click.stop="dialogVisible = false" class="cancel-button">取消</el-button>
        <el-button type="primary" :disabled="uploadSubmitFlag" @click.stop="submitUploadDoc" color="#00A298">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog
      v-model="centerDialogVisible"

      title="文件重命名"
      @closed="handleClosed"
      width="30%"
      @click="stopProp"
      align-center
  >
    <el-form :model="form" label-width="120px" ref="ruleFormRef" class="demo-ruleForm">
      <el-row>
        <el-col :span="20">
          <el-form-item label="文件夹名称:" prop="name" :rules="[
                {
                  required: true,
                  message: '请输入文件夹名称',
                  trigger: 'blur',
                }
              ]">
            <el-input v-model="form.name" placeholder="请输入"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="centerDialogVisible = false" color="#DFEFEC" class="cancel-button">取消</el-button>
        <el-button type="primary" @click="updateName(ruleFormRef)" color="#00A298">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog
      v-model="moveFlag"
      :title="moveDialogTitle"
      align-center
      @click="stopProp"
      @closed="handleClosed"
      width="30%"

  >
    <el-form label-width="120px" class="demo-ruleForm" ref="moveRuleFormRef" :model="moveForm">

      <el-form-item label="文件类别:" prop="moveDirectoryType" :rules="[
                    {
                    required: true,
                    message: '请选择文件类别',
                    trigger: 'blur',
      }
      ] ">
        <el-select v-model="moveDirectoryType" placeholder="请选择" @change="changeSelectOption">
          <el-option
              v-for="item in directoryType"
              :key="item.value"
              :label="item.text"
              :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="上级文件夹:" :rules="[
                {
                  required: moveDialogTitle==='移动文件',
                  message: '请选择上级文件夹',
                  trigger: 'blur'
            }]" prop="parentId">
        <el-tree-select
            :props="defaultProps"
            v-model="treeValue"
            :data="treeData"
            check-strictly
            @change="handleMoveParentDirChange"
            :render-after-expand="false"
            placeholder="请选择"
        />
      </el-form-item>

      <div v-show="false">
        <el-form-item label="显示排序" prop="orderNum">
          <el-input-number v-model="moveForm.moveOrderNum" controls-position="right" :min="1"
                           :max="maxSort"/>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="moveFlag = false" color="#DFEFEC" class="cancel-button">取消</el-button>
        <el-button type="primary" @click="moveDirectory(moveRuleFormRef)" color="#00A298">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog

      v-model="newDirDialogVisible"
      title="新建文件夹"
      width="30%"
      @closed="handleClosed"
      @close="closeDialog"
      align-center
      @click="stopProp"
  >
    <el-form :model="newDirForm" :rules="rules" label-width="120px" ref="newDirRuleFormRef" class="demo-ruleForm">
      <el-form-item label="文件夹名称:" prop="name">
        <el-input v-model="newDirForm.name" placeholder="请输入" style="width: 75%"/>
      </el-form-item>
      <el-form-item label="显示排序" prop="orderNum">
        <el-input-number v-model="newDirForm.orderNum" controls-position="right"  :min="1"
                         style="width:37%"/>
      </el-form-item>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm(newDirRuleFormRef)" color="#00A298">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog v-model="newMarkdownVisible"
             title="新建Markdown"
             align-center
             @click="stopProp"
             @closed="handleClosed"

             width="30%">
    <el-form :model="newMarkdownForm" label-width="120px" ref="newMarkdownFormRef" class="demo-ruleForm">
      <el-form-item label="文件名称:" prop="name" :rules="[
                {
                  required: true,
                  message: '请输入markdown文件名',
                  trigger: 'blur',
                }
              ]">
        <el-input v-model="newMarkdownForm.name" placeholder="请输入" style="width:75%"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelNewMarkdown">取消</el-button>
        <el-button type="primary" @click="submitNewMarkdown(newMarkdownFormRef)" color="#00A298">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>

</template>
<script>
import {inject, reactive, ref, toRefs} from 'vue'
import ArrowDownload from '@/components/common/ArrowDownload'
import DeleteIcon from '@/components/common/DeleteIcon'
import MoveToIcon from '@/components/common/MoveToIcon'
import EditIcon from '@/components/common/EditIcon'
import StarIcon from '@/components/common/StarIcon'
import {computed} from "@vue/reactivity"
import FolderIcon from '@/components/document/FolderIcon.vue'
import ExcelIcon from '@/components/document/ExcelIcon.vue'
import WordIcon from '@/components/document/WordIcon.vue'
import PptIcon from '@/components/document/PptIcon.vue'
import UnknownIcon from '@/components/document/UnknownIcon.vue'
import PdfIcon from '@/components/document/PdfIcon.vue'
import JpgIcon from '@/components/document/JpgIcon.vue'
import Mp4Icon from '@/components/document/Mp4Icon'
import DateFormatPipe from "../../utils/dateFormat.js";
import FrontApi from '@/api/front'
import {download} from '@/api/request'
import {ElMessage, ElMessageBox} from "element-plus";
import UploadFile from "../common/UploadFile"
import eventBus from '@/utils/event_bus'
import {Base64} from "js-base64";
import {selectSpaceFileUrl} from '@/api/document'
import TxtIcon from "@/components/document/TxtIcon";
import XmindIcon from "@/components/document/XmindIcon";
import MdIcon from "@/components/document/MdIcon";
import HexIcon from "@/components/document/HexIcon"
import MarkdownArrow from "@/components/common/MarkdownArrow";

export default {
  components: {
    ArrowDownload,
    MarkdownArrow,
    DeleteIcon,
    MoveToIcon,
    EditIcon,
    StarIcon,
    ExcelIcon,
    WordIcon,
    PptIcon,
    UnknownIcon,
    PdfIcon,
    FolderIcon,
    UploadFile,
    JpgIcon,
    TxtIcon,
    XmindIcon,
    MdIcon,
    HexIcon,
    Mp4Icon
  },
  props: {
    document: {
      type: Object
    },
    dragFlag: {
      type: Boolean,
      default: false
    }
  },
  emits: ["update:dragFlag"],
  setup(props, {emit}) {
    const treeValue = ref()
    const moveDirectoryType = ref()
    const defaultProps = {  //规定
      children: "children",
      label: "name",
      value: "id"
    };
    const ruleFormRef = ref();
    const moveRuleFormRef = ref();
    const newMarkdownFormRef = ref(null)
    const centerDialogVisible = ref(false)
    const moveFlag = ref(false)
    const typeData = ref(props.document.cType || 'folder')
    const fileNameData = ref(props.document.name)
    const catalogueType = ref(props.document.type)
    const authorData = ref(props.document.createBy)
    const dateData = ref(props.document.createTime)
    const documentId = ref(props.document.documentId)
    const moveDialogTitle = ref(documentId.value ? '移动文件' : '移动文件夹')
    const directoryId = ref(props.document.id)
    const ancestors = ref(props.document.ancestors)
    const parentDirectoryId = ref(props.document.parentId)
    const flag = ref(props.document.isCollection)
    const level = ref(props.document.level)
    const uploadSubmitFlag = ref(true)
    const uploadFiles = ref([])
    const uploadRef = ref(null)
    //新建文件夹
    const newDirDialogVisible = ref(false)
    const newDirRuleFormRef = ref()
    const idValue = ref()
    const typeSelect = inject("typeSelect")
    const newMarkdownVisible = ref(false)
    const maxSort = ref(1)

    var newDirForm = reactive({
      parentId: idValue,
      name: '',
      type: null,
      orderNum: 1
    })

    var newMarkdownForm = reactive({
      parentId: idValue,
      name: '',
      type: null,
    })

    var form = reactive({
      name: '',
      id: null
    })
    var moveForm = reactive({
      parentId: treeValue,
      moveDirectoryType: null,
      moveOrderNum: 1
    })
    var data = reactive({
      treeData: []
    })
    const fileType = computed(() => {
      return (type) => {
        const typeMap = {
          'doc': 'WordIcon',
          'docx': 'WordIcon',
          'ppt': 'PptIcon',
          'pptx': 'PptIcon',
          'pdf': 'PdfIcon',
          'xls': 'ExcelIcon',
          'xlsx': 'ExcelIcon',
          'folder': 'FolderIcon',
          'jpg': 'JpgIcon',
          'png': 'JpgIcon',
          'jpeg': 'JpgIcon',
          'xmind': 'XmindIcon',
          'md': 'MdIcon',
          'txt': 'TxtIcon',
          'hex': 'HexIcon',
          'mp4': 'Mp4Icon'
        }
        return typeMap[type.toLowerCase()] || 'UnknownIcon'
      }
    })
    const type = ref([])
    const directoryType = ref([])
    const uploadFileForm = ref(null)
    const dialogVisible = ref(false)
    let uploadForm = reactive({
      name: '',
      type: '',
      suffix: '',
      description: '',
      author: '',
      fileId: '',
      fileUrl: '',
      fileName: '',
      directoryName: props.document.name,
      directoryType: catalogueType.value,
      fileTypeName: ''
    })

    const copyText = () => {
      selectSpaceFileUrl(documentId.value).then(res => {
        var fileUrl = process.env.VUE_APP_MINIO_NETWORK + res.data.replace('/storage', '')
        var input = document.createElement("input");   // js创建一个input输入框
        input.value = process.env.VUE_APP_PREVIEW_API + '/onlinePreview?url=' + encodeURIComponent(Base64.encode(fileUrl))// 将需要复制的文本赋值到创建的input输入框中，this.ruleForm.url这个是我要复制的内容
        document.body.appendChild(input);    // 将输入框暂时创建到实例里面
        input.select();   // 选中输入框中的内容
        document.execCommand("Copy");   // 执行复制操作
        document.body.removeChild(input); // 最后删除实例中临时创建的input输入框，完成复制操作
        ElMessage({
          message: '文档链接已复制到剪贴板', // 这里是提示信息
          type: 'success', //
        })
      })

    }

    const stopProp = (e) => {
      e.stopPropagation()
    }

    const submitUploadDoc = () => {
      FrontApi.addSpaceDocument(uploadFiles.value).then(res => {
        if (res.code === 200) {
          eventBus.emit("updateCatalogueBus", catalogueType.value)
          dialogVisible.value = false
          ElMessage({
            message: '添加成功',
            type: 'success',
          })
          uploadForm.name = ''
          uploadForm.fileTypeName = ''
          uploadForm.suffix = ''
          uploadForm.fileUrl = ''
          uploadForm.fileId = ''
          uploadForm.type = ''
        }
      })
    }
    const moveDirectory = (ruleForm) => {
      let id = directoryId.value;
      let parentId = treeValue.value;
      let oldParentId = parentDirectoryId.value
      let oldOrderNum = props.document.orderNum
      let type = moveForm.moveDirectoryType;
      if (!parentId) {
        parentId = 0;
      }
      if (id === parentId) {
        ElMessage({
          message: '无法选择当前文件夹',
          type: 'error',
        })
        moveForm = null
        return false;
      }
      ruleForm.validate((valid) => {
        if (valid) {
          FrontApi.moveDirectory(id, oldParentId, parentId, type, oldOrderNum).then(res => {
            if (res.code === 200) {
              ElMessage({
                message: '移动成功',
                type: 'success',
              })
              let obj = {
                originType: catalogueType.value,
                targetType: type
              }
              eventBus.emit("moveDirectoryBus", obj)
              moveForm = null
              moveFlag.value = false;
            } else {
              ElMessage({
                message: '移动失败',
                type: 'error',
              })
            }
          })
        } else {
          return false;
        }
      })
    }
    const moveFileOrDirectory = () => {
      emit("update:dragFlag", false)
      moveDirectoryType.value = null;
      getDirectoryType();
      moveFlag.value = true
    }
    const changeSelectOption = (val) => {
      moveForm.moveOrderNum = 1;
      FrontApi.getMaxOrder(val, 0).then((res) => {
        maxSort.value = res.data === undefined ? 1 : res.data + 1
      })
      data.treeData = [];
      treeValue.value = null;
      moveForm.moveDirectoryType = val;
      if (typeof (documentId.value) == "undefined") {
        FrontApi.getFirstIndexSpaceDirectoryTree(null).then(res => {
          directoryDataFilter(res);
        })
      } else if (typeof (documentId.value) != "undefined") {
        FrontApi.getDirectorySelectTree().then(res => {
          directoryDataFilter(res);
        });
      }
    }

    const handleMoveParentDirChange = (val) => {
      moveForm.moveOrderNum = 1;
      FrontApi.getMaxOrder(null, val).then((res) => {
        maxSort.value = res.data === undefined ? 1 : res.data + 1
      })
    }

    const directoryDataFilter = (res) => {
      res.data.forEach(e => {
        var type = e.type + '';
        if (type === moveDirectoryType.value) {
          data.treeData.push(e)
        }
      })
    }
    const removeUploadFile = obj => {
      if (obj.file && obj.file?.status === "success") {
        if (!uploadFiles.value || uploadFiles.value.length === 0) {
          return ""
        }
        uploadFiles.value = uploadFiles.value.filter((item) => {
          return item["name"] !== obj.file.name
        })
      }
      if (obj.file === null && obj.allRemoveFlag) {
        uploadFiles.value = []
      }
      if (uploadFiles.value.length === 0) {
        uploadSubmitFlag.value = true
      }
    }

    const allUploadSuccess = () => {
      uploadSubmitFlag.value = false
    }

    const addCollection = () => {
      var id = documentId.value;
      FrontApi.addCollection(id).then(res => {
        if (res.code === 200) {
          eventBus.emit("updateCatalogueBus", catalogueType.value);
          flag.value = 1;
          ElMessage({
            message: '收藏成功',
            type: 'success',
          })
        } else {
          ElMessage({
            message: '收藏失败',
            type: 'error',
          })
        }
      })
    }
    const removeCollection = () => {
      var id = documentId.value;
      FrontApi.removeCollection(id).then(res => {
        if (res.code === 200) {
          eventBus.emit("updateCatalogueBus", catalogueType.value);
          flag.value = 0;
          ElMessage({
            message: '取消成功',
            type: 'success',
          })
          flag.value = 0;
        } else {
          ElMessage({
            message: '取消失败',
            type: 'error',
          })
        }
      })

    }

    const uploadDialogClose = () => {
      uploadForm.name = ''
      uploadForm.fileTypeName = ''
      uploadForm.fileName = null
      uploadForm.suffix = ''
      uploadForm.fileUrl = ''
      uploadForm.fileId = ''
      uploadForm.type = ''
      uploadFiles.value = []
    }

    const echoName = () => {
      emit("update:dragFlag", false)
      var id = directoryId.value;
      FrontApi.getEchoDirectory(id).then(res => {
        form.name = res.data.name;
        form.id = res.data.id;

      })
      centerDialogVisible.value = true;
    }

    const fillForm = res => {
      let fileName = res.originFileName
      uploadForm.name = fileName

      let suffix = res.suffix
      uploadForm.suffix = suffix
      uploadForm.fileUrl = res.fileUrl

      let fileId = res.fileId
      uploadForm.fileId = fileId
      uploadForm.type = res.fileTypeId
      uploadForm.fileTypeName = res.fileTypeName
      uploadFiles.value.push({
        name: fileName,
        suffix: suffix,
        fileUrl: res.fileUrl,
        fileId: fileId,
        type: res.fileTypeId,
        fileTypeName: res.fileTypeName,
        directoryName: props.document.name,
        parentDirectoryId: props.document.id,
        directoryType: catalogueType.value,
      })
    }

    //正在上传文件钩子
    const onProgressUpload = () => {
      uploadSubmitFlag.value = true
    }

    const updateName = () => {
      ruleFormRef.value.validate((valid) => {
        if (valid) {
          FrontApi.updateSpaceDirectory(form).then(res => {
            if (res.code === 200) {
              eventBus.emit("updateCatalogueBus", catalogueType.value)
              ElMessage({
                message: '修改成功',
                type: 'success',
              })
              centerDialogVisible.value = false;
              fileNameData.value = form.name;
            } else {
              ElMessage({
                message: '修改失败',
                type: 'error',
              })
            }
          })
        } else {
          return false;
        }
      })

    }
    const uploadFileButton = () => {
      emit("update:dragFlag", false)
      uploadForm.name = ''
      uploadForm.suffix = ''
      uploadForm.fileUrl = ''
      uploadForm.fileId = ''
      dialogVisible.value = true
      uploadSubmitFlag.value = true
      getDocumentType()
      getDirectoryType()
    }


    const getDocumentType = () => {
      type.value.length = 0
      FrontApi.getDocumentType().then(res => {
        res.data.forEach(e => {
          const t = {
            "text": e.dictLabel,
            "value": e.dictValue
          }
          type.value.push(t);
        })
      })
    }

    const getDirectoryType = () => {
      directoryType.value.length = 0
      FrontApi.getDirectoryType().then(res => {
        res.data.forEach(e => {
          const t = {
            "text": e.dictLabel,
            "value": e.dictValue
          }
          directoryType.value.push(t);
        })
      })
    }

    const uploadFile = () => {
      dialogVisible.value = true
    }
    const downloadDocument = () => {
      var spaceDocId = documentId.value;
      download('/admin/front/downloadFile', {'spaceDocId': spaceDocId}, fileNameData.value);
    }
    const removefile = () => {
      var id = directoryId.value;
      ElMessageBox.confirm(
          '确定删除当前文件?',
          '删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            confirmButtonClass: 'confirmButton'
          }
      ).then(() => {
        FrontApi.removeSpaceDirectory(id).then(res => {
          if (res.code === 200) {
            eventBus.emit("updateCatalogueBus", catalogueType.value)
            ElMessage({
              message: '删除成功',
              type: 'success',
            })
          } else {
            ElMessage({
              message: '删除失败',
              type: 'error',
            })
          }
        })
      })
          .catch(() => {
            ElMessage({
              type: 'info',
              message: '取消删除',
            })
          })
    }

    const cancel = () => {
      newDirDialogVisible.value = false;
      newDirRuleFormRef.value.resetFields()
    }

    const cancelNewMarkdown = () => {
      newMarkdownVisible.value = false;
      newMarkdownFormRef.value.resetFields()
    }

    const validateName = (rule, value, callback) => {
      if (value === '' || value === undefined) {
        callback(new Error('请输入文件夹名称'))
      }
      callback()
    }

    //表单校验
    const rules = reactive({
      name: [{validator: validateName, trigger: 'blur', required: true}]
    })

    const submitNewMarkdown = (ruleForm) => {
      ruleForm.validate((valid) => {
        if (valid) {
          let mark_blob = new Blob(["# 新建markdown"])
          let filename = newMarkdownForm.name.trim()
          if (!filename.endsWith(".md") && !filename.endsWith(".markdown")) {
            filename = filename + ".md"
          }
          let file = new File([mark_blob], filename)
          FrontApi.addMarkdown(file, newMarkdownForm.parentId, newMarkdownForm.type).then(res => {
            if (res.code === 200) {
              eventBus.emit("updateCatalogueBus", newMarkdownForm.type)
              ElMessage({
                message: '添加成功',
                type: 'success',
              })
              newMarkdownVisible.value = false;
              newMarkdownFormRef.value.resetFields()
            } else {
              ElMessage({
                message: '添加失败',
                type: 'error',
              })
            }
          })
        } else {
          return false;
        }
      })
    }

    const submitForm = (ruleForm) => {
      ruleForm.validate((valid) => {
        if (valid) {
          FrontApi.addSpaceDirectory(newDirForm).then(res => {
            if (res.code === 200) {
              eventBus.emit("updateCatalogueBus", newDirForm.type)
              ElMessage({
                message: '添加成功',
                type: 'success',
              })
              newDirDialogVisible.value = false;
              newDirRuleFormRef.value.resetFields()
            } else {
              ElMessage({
                message: '添加失败',
                type: 'error',
              })
            }
          })
        } else {
          return false;
        }
      });
    }

    const closeDialog = () => {
      newDirRuleFormRef.value.resetFields()
    }

    const handleClosed = () => {
      emit("update:dragFlag", true)
    }

    const handleClose = (done) => {
      ElMessageBox.confirm(
          '确定关闭该窗口?',
          '关闭',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            confirmButtonClass: 'confirmButton'
          }
      ).then(() => {
        done()
      })
    }

    const openNewDirDialog = () => {
      emit("update:dragFlag", false)
      newDirForm.parentId = directoryId.value
      newDirForm.type = catalogueType.value
      newDirDialogVisible.value = true;
    }

    const openNewMarkdown = () => {
      emit("update:dragFlag", false)
      newMarkdownForm.parentId = directoryId.value
      newMarkdownForm.type = catalogueType.value
      newMarkdownVisible.value = true
    }

    return {
      moveDirectoryType,
      typeData,
      newDirDialogVisible,
      newDirForm,
      openNewDirDialog,
      submitForm,
      newDirRuleFormRef,
      newMarkdownVisible,
      cancel,
      getDocumentType,
      getDirectoryType,
      validateName,
      uploadFile,
      rules,
      openNewMarkdown,
      submitNewMarkdown,
      newMarkdownForm,
      type,
      directoryType,
      closeDialog,
      submitUploadDoc,
      dialogVisible,
      fileNameData,
      typeSelect,
      authorData,
      dateData,
      directoryId,
      uploadSubmitFlag,
      fillForm,
      moveDialogTitle,
      fileType,
      handleClosed,
      DateFormatPipe,
      downloadDocument,
      removefile,
      updateName,
      centerDialogVisible,
      echoName,
      handleMoveParentDirChange,
      uploadFileButton,
      uploadForm,
      form,
      uploadFileForm,
      cancelNewMarkdown,
      addCollection,
      removeCollection,
      flag,
      catalogueType,
      allUploadSuccess,
      newMarkdownFormRef,
      uploadDialogClose,
      stopProp,
      treeValue,
      defaultProps,
      ...toRefs(data),
      moveFlag,
      moveDirectory,
      handleClose,
      documentId,
      onProgressUpload,
      level,
      ruleFormRef,
      moveFileOrDirectory,
      parentDirectoryId,
      removeUploadFile,
      copyText,
      changeSelectOption,
      moveRuleFormRef,
      moveForm,
      uploadRef,
      ancestors, maxSort
    }
  },
  methods: {
    visibleChange(flag) {
      if (flag) {
        this.$refs.oneFileOrDir.parentNode.style.background = '#F3F6FC'
        this.$refs.oneFileOrDir.style.display = 'none'
        this.$refs.oneFileOrDirHover.style.display = 'flex'
      } else {
        this.$refs.oneFileOrDir.style = {}
        this.$refs.oneFileOrDirHover.style = {}
        this.$refs.oneFileOrDir.parentNode.style = {}
      }
    }
  }
}
</script>
<style scoped lang="scss">
.one-file-or-dir {
  display: flex;
  flex: 1;
  align-items: center;
  position: relative;
  z-index: 1;
  height: 100%;
}

.one-file-or-dir-hover {
  flex: 1;
  align-items: center;
  display: none;
  height: 100%;
  margin-right: 1rem;
}

.folder-icon-wrap {
  color: #fbc86a;
}

.file-or-dir-wrap {
  font-size: 1.7rem;
  display: inline-flex;
  align-items: center;
  white-space: nowrap;
  margin-right: 1rem;
  margin-left: 0.5rem;
}

.author-and-date {
  width: 20rem;
  display: inline-flex;
  align-items: center;
}

.author {
  width: 10rem;
  font-weight: 400;
  color: var(--el-text-color-regular);
  font-size: 1.6rem;
  white-space: nowrap;
  text-align: right;
  justify-content: end;
}

.date {
  font-weight: 400;
  color: var(--el-text-color-regular);
  white-space: nowrap;
  text-align: right;
  margin-right: 10px;

}

.editor-wrap {
  height: 100%;
  display: flex;
  position: absolute;
  right: 1.2rem;
  align-items: center;
}

.more {
  margin-right: 0.8rem;
  height: 4.8rem;
  display: inline-flex;
  align-items: center;

}

.icon-wrap {
  width: 3.2rem;
  height: 3.2rem;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.icon-wrap:hover {
  background: var(--el-color-info-light-8);
}

.more img {
  height: 0.4rem;
  margin-top: 2rem;
  margin-bottom: 2rem;
}

.share {
  margin-right: 0.8rem;
}

.share img {
  height: 1.7rem;
}

.new {
  height: 2.2rem !important;
}

:deep(.el-popper__arrow) {
  display: none;
}

.cancle {
  border-color: #61C9B8;
  color: #00A298
}

.el-select {
  --el-select-input-focus-border-color: #00A298;
}

.el-input {
  --el-input-focus-border: #00A298;
  --el-input-focus-border-color: #00A298;
}

.el-divider--horizontal {
  margin: 0 !important;
}

.upload-card {
  border: 2px dashed var(--el-text-color-placeholder);
  min-height: 28rem;
}


.el-dialog__body {
  padding-top: 1rem !important;
  padding-bottom: 1rem !important;
}

.el-dropdown-menu__item i {
  width: 20px !important;
  height: 20px !important;

  svg {
    width: 18px !important;
    height: 18px !important;
  }
}
</style>
